<?php

namespace app\common\business;

use app\common\lib\Curl;
use app\common\lib\Status;
use app\common\lib\Str;
use app\common\lib\Time;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\facade\Cache;

class UserInfo
{

    public $model = null;

    public function __construct()
    {
        $this->model = new \app\common\model\mysql\UserInfo();
    }

    /**
     * @param $where
     * @param $page
     * @param $limit
     * @param string $field
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getListByWhere($where,$page,$limit,$field='*'){
        $where[] = ['status','=',config("status.mysql.table_normal")];
        if ($page!=0 && $limit !=0){
            $list = $this->model->getPageListByWhere($where,$page,$limit,$field);
        }else{
            $list = $this->model->getNormalListByWhere($where,$field);
        }
        if($list->isEmpty()){
            return [];
        }
        return $list->toArray();
    }

    public function updateData($user_id, $data)
    {
        $user = (new User())->getJoinNormalUserByField('userLabor','id',$user_id);
        //$user = (new User())->getNormalUserById($user_id);
        if (!$user) {
            throw new Exception("不存在该用户");
        }
        $userLabor = UserLabor::checkIsLabor($user['userLabor']);
        if ($userLabor == 1){
            throw new Exception("劳务派遣公司身份不可编辑个人求职信息");
        }

        $info = self::getNormalSimpleInfoByField('user_id',$user_id);
        if (!$info) {
            throw new Exception("不存在该用户");
        }

        $userInfoId = $info['id'];
        try {
            $res = $this->model->updateById($userInfoId,$data);
        } catch (\Exception $e) {
            throw new Exception("数据库内部异常");
        }
        return $res;
    }

    public function getNormalInfoByField($field,$value)
    {
        $user = $this->model->getNormalByField($field,$value);
        $user=!$user || $user->status != config("status.mysql.table_normal")?[]:$user->toArray();
        return self::resetUserInfo($user);
    }

    public function getNormalSimpleInfoByField($field,$value)
    {
        $data = $this->model->getNormalByField($field,$value);
        if (!$data || $data->status != config("status.mysql.table_normal")) {
            return [];
        }
        $data=$data->toArray();
        return $data;
    }

    public function getInfoSkillLabelByField($field,$value)
    {
        $workType=(new WorkType())->getChildDictionaries();
        $data = $this->model->getNormalByField($field,$value);
        if (!$data || $data->status != config("status.mysql.table_normal")) {
            return [];
        }
        $data=$data->toArray();
        if(isset($data['skill_label'])&&!empty($data['skill_label'])){
            $skillLabel=explode(',',$data['skill_label']);
            $skillLabelData=[];
            foreach ($skillLabel as $v){
                $skillLabelData[]=$workType[$v];
            }
            $data['skill_label']=$skillLabelData;
        }else{
            $data['skill_label']=[];
        }
        return $data;
    }

    public function saveData($user_id, $data)
    {
        $userBis = new User();
        $user = $userBis->getJoinNormalUserByField('userInfo','id',$user_id);
        if (!$user) {
            throw new Exception("不存在该用户");
        }

        //必须实名认证
        $autherizedFlag = $userBis->checkIsAutherized($user['autherized']);
        if (!$autherizedFlag){
            throw new Exception("只有通过实名认证的用户才能操作");
        }

        //检查是否已提交
        if ($this->checkIsSubmitHomeAutherized($user['userInfo'])){
            throw new Exception("请勿重复提交房屋认证");
        }

        //检查房屋人员信息表 有的话直接通过认证，没有则需要后台审核
        $housePersonBis = new HousePerson();
        $mapHousePerson = [
            ['person_name','=',$user['name']],
            ['person_idcard','=',$user['id_card']]
        ];
        $housePersonExist = $housePersonBis->getNormalByWhere($mapHousePerson,'id,status');
        if (!empty($housePersonExist)){
            //后台已导入该人员房屋信息，直接认证通过
            $data['house_person_id'] = $housePersonExist['id'];
            $data['check_status'] = 2;//已通过
        }else{
            //后台未导入该人员相关房屋信息，需要后台审核
            //审核通过后将人员房屋信息添加到house_person表
            $data['house_person_id'] = 0;
            $data['check_status'] = 1;//待审核
        }

        try {
            $res = $this->model->updateById($user['userInfo']['id'],$data);
        } catch (\Exception $e) {
            throw new Exception($e->getMessage());
        }

        return $res;
    }

    /**
     * 判断是否房屋认证
     * @param $data
     * @return bool
     */
    public function checkIsHomeAutherized($data){
        $flag = false;

        if ($data['check_status'] == 2){
            $flag = true;
        }
        return $flag;
    }

    /**
     * 判断是否提交房屋认证
     * true提交 false未提交
     * @param $data
     * @return bool
     */
    public function checkIsSubmitHomeAutherized($data){
        $flag = false;

        //未提交或拒绝可提交
        if ($data['check_status'] != 0 && $data['check_status'] != 3){
            $flag = true;
        }
        return $flag;
    }

    public static function resetUserInfo($data){
        if (empty($data)){
            return [];
        }

        $data['house_ids_text'] = '';
        if (!empty($data['house_ids'])){
            $houseIds = explode(',',$data['house_ids']);
            $mapHouse = [
                ['id','in',$houseIds],
                ['status','=',config('status.mysql.table_normal')]
            ];
            $houseList = (new \app\common\model\mysql\House())->where($mapHouse)->orderRaw('field(id,'.$data['house_ids'].')')->field('id,pid,name')->select();
            if (!$houseList->isEmpty()){
                $houseList = $houseList->toArray();

                $houseNameArr = array_column($houseList,'name');
                $data['house_ids_text'] = implode('',$houseNameArr);
            }
        }

        $userInfoConfig = config('user_info');
        $data['is_host_text'] = $userInfoConfig['is_host'][$data['is_host']] ?? '';
        $data['check_status_text'] = $userInfoConfig['check_status'][$data['check_status']] ?? '';
        return $data;
    }

    public function updateDataByWhere($where,$data): bool
    {
        return $this->model->where($where)->save($data);
    }

    /**
     * 审核房屋信息
     * @param $uid
     * @param $check_status
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public function audit($uid,$check_status){
        $userBis = new User();
        $user = $userBis->getJoinNormalUserByField('userInfo','id',$uid);
        if (!$user) {
            throw new Exception("不存在该用户");
        }

        //审核代表住户暂时未入houseperson住户库，需要新增
        $housePersonData = [
            'house_ids' => $user['userInfo']['house_ids'],
            'person_name' => $user['name'],
            'person_idcard' => $user['id_card'],
            'person_phone' => $user['phone_number'],
            'is_host' => $user['userInfo']['is_host'],
            'status' => config('status.mysql.table_normal'),
            'create_time' => time(),
        ];
        try {
            $this->model->save($housePersonData);
        } catch (\Exception $e) {
            throw new Exception("数据库内部异常");
        }

        $housePersonId = $this->model->id;

        //更新userInfo
        $daoSave = $this->model->where(['user_id'=>$uid])->save(['check_status'=>$check_status,'house_person_id'=>$housePersonId]);
        return $daoSave;
    }
}
